package com.yusp75.myexam.ui.exam


import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.yusp75.myexam.com.yusp75.myexam.data.AnswerResultMap
import com.yusp75.myexam.com.yusp75.myexam.data.QuestionRepository
import com.yusp75.myexam.di.DataHolder
import kotlinx.coroutines.launch

class ExamResultViewModel(
    private val repository: QuestionRepository,
    private val holder: DataHolder
) : ViewModel() {

    private val _failureQuestions = MutableLiveData<List<AnswerResultMap>>()
    val failureQuestions: LiveData<List<AnswerResultMap>> = _failureQuestions

    // 分数计算
    val score = holder.run {
        if (questionNum > 0) (100f * (questionNum - resultOfAnswers.size)) / questionNum else 0f
    }
    val scoreTxt =
        "题目数：${holder.questionNum}，错误：${holder.resultOfAnswers.size}，得分：${"%.1f".format(score)}"

    val totalTimeTxt = "做题总时间：${holder.totalTimeElapsed / 1000}s"

    init {
        viewModelScope.launch {
            _failureQuestions.value = repository.mapAnswersToQuestions(holder.resultOfAnswers)
        }
    }

}